package middleware

import (
	"net/http"
	"note-go/session"
	"strings"

	"github.com/gin-gonic/gin"
)

func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		sessionID, err := c.Cookie("session_id")
		if err != nil || sessionID == "" {
			if !strings.HasPrefix(c.Request.URL.Path, "/login") && !strings.HasPrefix(c.Request.URL.Path, "/.well-known") {
				c.Redirect(http.StatusSeeOther, "/login")
			} else {
				c.Next()
			}
			c.Abort()
			return
		}
		_, err = session.GetSession(sessionID)
		if err != nil {
			c.Redirect(http.StatusSeeOther, "/login")
			c.Abort()
			return
		}
		c.Next()
	}
}
